<template>
  <view v-if="!loading">
    <view>
      <u-tabs-swiper
        ref="uTabs"
        :list="tabList"
        :current="current"
        @change="tabsChange"
        :is-scroll="false"
        swiperWidth="750"
      ></u-tabs-swiper>
    </view>
    <swiper
      :class="[
        'swiper',
        {
          noButton: !(
            taskInfo.approvalPermission || taskInfo.urgeSignPermission === 1
          ),
        },
      ]"
      :current="swiperCurrent"
      @transition="transition"
      @animationfinish="animationfinish"
    >
      <swiper-item
        class="swiper-item"
        v-for="(item, index) in tabList"
        :key="index"
      >
        <!-- height: ${
            px2rpx(screenHeight) - (taskInfo.approvalPermission ? 120 : 0)
          }rpx;  -->
        <scroll-view
          class="content-page"
          scroll-y
          :style="`width: 100%`"
          @scrolltolower="onreachBottom"
        >
          <!-- {{ tabList[swiperCurrent].name }} -->
          <base-com
            v-if="
              tabList[swiperCurrent].name === '任务信息' &&
              swiperCurrent === index
            "
            :taskInfo="taskInfo"
            :projectInfo="projectInfo"
          />
          <DependenciesCom
            v-if="
              tabList[swiperCurrent].name === '依赖关系' &&
              swiperCurrent === index
            "
            :taskInfo="taskInfo"
          ></DependenciesCom>
          <feedback
            v-if="
              tabList[swiperCurrent].name === '反馈信息' &&
              swiperCurrent === index
            "
            :taskInfo="taskInfo"
          ></feedback>
          <fileList
            ref="refFileList"
            v-if="
              tabList[swiperCurrent].name === '文件清单' &&
              swiperCurrent === index
            "
            :taskInfo="taskInfo"
          ></fileList>
        </scroll-view>
      </swiper-item>
    </swiper>

    <view
      v-if="
        taskInfo.approvalPermission ||
        taskInfo.urgeSignPermission === 1 ||
        taskInfo.feedbackPermission
      "
      class="btn-box u-flex u-row-between fileList-sign-btn"
    >
      <u-button
        :class="[taskInfo.approvalPermission ? 'urge-sign' : '']"
        v-if="taskInfo.urgeSignPermission === 1"
        :style="{ flex: taskInfo.approvalPermission ? 0 : 1 }"
        shape="circle"
        type="primary"
        plain
        :loading="urgeSignLoading"
        @click="expeditingSign"
        >催签</u-button
      >
      <u-button
        v-if="taskInfo.approvalPermission"
        shape="circle"
        type="primary"
        @click="gotoApproval"
        >{{ taskInfo.taskStatus === 8 ? '受理' : '审批' }}</u-button
      >
      <u-button
        v-if="taskInfo.feedbackPermission"
        shape="circle"
        type="primary"
        @click="gotoFeedback"
        >{{ statusFlag(['returned']) ? '修改反馈' : '反馈' }}</u-button
      >
    </view>
  </view>
  <taskDetailSkeleton v-if="loading" />
</template>
<script lang="ts" setup>
import { TaskStatusEnum } from '../index';
import { useUserStoreWidthOut } from '@/stores/user';
import { usePermission } from '@/hooks/usePermission';
import { onLoad } from '@dcloudio/uni-app';
import { taskBaseInfo } from '@/api/modules/project';
import baseCom from './components/base.vue';
import DependenciesCom from './components/Dependencies.vue';
import fileList from '@/components/fileList/index.vue';
import feedback from './components/feedback.vue';
import { useBack } from '@/hooks/useBack';
import taskDetailSkeleton from './taskDetailSkeleton.vue';
import { urgeSign } from '@/api/modules/signFile';
const list = ref([
  {
    name: '任务信息',
  },
  {
    name: '依赖关系',
  },
  {
    name: '反馈信息',
  },
  // {
  //   name: '表单配置',
  // },
  // {
  //   name: '文件配置',
  // },
  {
    name: '文件清单',
  },
]);
const taskInfo = ref<any>({ viewPermission: false, memberList: [] });
const taskFileInfo = ref<any>({});
const spinning = ref(true);
const current = ref(0);
const swiperCurrent = ref(0);

const tabsChange = (index: number) => {
  swiperCurrent.value = index;
};
// swiper-item左右移动，通知tabs的滑块跟随移动
const uTabs = ref();
const transition = (e: any) => {
  let dx = e.detail.dx;
  uTabs.value.setDx(dx);
};
// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
// swiper滑动结束，分别设置tabs和swiper的状态
const animationfinish = (e: any) => {
  let curr = e.detail.current;
  uTabs.value.setFinishCurrent(curr);
  swiperCurrent.value = curr;
  current.value = curr;
};

const onreachBottom = () => {};

function statusFlag(status: any): boolean {
  if (Array.isArray(status)) {
    status = status.map((item: any) => {
      return TaskStatusEnum[item];
    });
  } else {
    status = [TaskStatusEnum[status]];
  }
  return status.includes(taskInfo.value.taskStatus);
}
const loading = ref(true);
const getTaskInfo = (taskId: any) => {
  loading.value = true;
  taskBaseInfo(taskId).then((res: any) => {
    taskInfo.value.taskId = undefined;
    nextTick(() => {
      taskInfo.value = Object.assign({}, res);
      spinning.value = false;
      // 如果存在候补任务
      if (res.sopTaskObject !== null) {
        taskFileInfo.value = Object.assign({}, res);
        taskFileInfo.value.taskId = res.sopTaskObject.taskId;
        taskFileInfo.value.needProcess = res.sopTaskObject.needProcess;
        // 如果任务状态不为已完成，那么后补任务沿用任务状态
        if (
          taskInfo.value.taskStatus !== 6 ||
          res.sopTaskObject.taskStatus === 1
        ) {
          // 如果立项任务是草稿，那么后补任务也是草稿
          if (taskInfo.value.taskStatus === 1) {
            taskFileInfo.value.taskStatus = 1;
          } else {
            taskFileInfo.value.taskStatus = 2;
          }
        } else {
          taskFileInfo.value.taskStatus = res.sopTaskObject.taskStatus;
        }
      }
      formatFormData();

      loading.value = false;
    });
  });
};

const personLiableType = ref(0); // 0: 指定人员 1: 指定角色

function formatFormData() {
  // taskInfo.value = Object.assign(taskInfo.value, taskInfo);
  // 任务时长如果没值，默认为1(自然日)
  taskInfo.value.durationUnit = taskInfo.value.durationUnit || 1;
  if (taskInfo.value.remindType && taskInfo.value.remindType.length > 0) {
    taskInfo.value.remindTypeChecked = true;
  }
  if (taskInfo.value.responsibilityType === 1) {
    personLiableType.value = 0;
    taskInfo.value.memberList = (
      taskInfo.value.responsibilityUserList || []
    ).map((item: any) => item.name);
  }
  if (taskInfo.value.responsibilityType === 2) {
    personLiableType.value = 1;
    taskInfo.value.memberList = (
      taskInfo.value.responsibilityRoleList || []
    ).map((item: any) => item.roleName);
  }
}

const tabList = computed(() => {
  const arr = list.value.filter((item) => {
    let flag = true;
    switch (item.name) {
      case '反馈信息':
        flag = !statusFlag(['draft', 'pendingFeedback', 'pendingSubmission']);
        break;
      case '表单配置':
        flag =
          canDelandRback &&
          statusFlag(['draft', 'pendingFeedback', 'pendingSubmission']);
        break;
      case '文件配置':
        flag =
          canDelandRback &&
          statusFlag(['draft', 'pendingFeedback', 'pendingSubmission']);
        break;
      case '文件清单':
        flag = !statusFlag(['draft', 'pendingFeedback', 'pendingSubmission']);
        break;
      default:
        flag = true;
        break;
    }
    return flag;
  });
  // 如果是电子签署状态 && 有文件清单的tab，手动改tab
  if (
    tab.value === 'filelist' &&
    arr.some((item) => item.name === '文件清单')
  ) {
    current.value = arr.findIndex((item) => item.name === '文件清单');
    swiperCurrent.value = arr.findIndex((item) => item.name === '文件清单');
    tab.value = '';
  }
  return arr;
});

// 是否发布人
const asyncUser: any = useUserStoreWidthOut();
const isPublishUser = computed((): boolean => {
  return (
    asyncUser.getOrgInfo?.accountId === taskInfo.value.createAccountId ||
    !taskInfo.value.createAccountId
  );
});
const { hasPermission } = usePermission();
// 是否可以撤回或发布
const canDelandRback = computed(() => {
  // 如果是项目里面，只有发布人可以撤回或删除
  if (taskInfo.value.sourceType === 'project') {
    return isPublishUser.value;
  }
  // 如果是在模板里面，需要有权限才能删除或者撤回
  return hasPermission(['CTMS-SOP-JDMB-OPER', 'CTMS-CONFIG-PROGRESS-INDEX']);
});

const gotoApproval = () => {
  let id = '';
  if (taskInfo.value.taskStatus === 4 || taskInfo.value.taskStatus === 8) {
    id = taskInfo.value.taskId;
  } else if (taskFileInfo.value.taskStatus === 4) {
    id = taskInfo.value.sopTaskObject.taskId;
  }
  (uni as any).$Router.push({
    name: 'approval',
    params: {
      id,
      taskType: taskInfo.value.taskType,
      supplementFile:
        taskInfo.value.taskType === 3 && taskFileInfo.value.taskStatus === 4
          ? true
          : undefined,
    },
  });
};
const gotoFeedback = () => {
  if (taskInfo.value.taskType === 1) {
    (uni as any).$Router.push({
      name: 'feedBack',
      params: {
        taskId: taskInfo.value.taskId,
        taskType: taskInfo.value.taskType,
        needFile: taskInfo.value.needFile,
        projectId: projectInfo.value.projectId,
      },
    });
  } else {
    uni.showToast({
      title: '暂不支持此类型的任务反馈，请前往pc端操作',
      icon: 'none',
      duration: 2000,
    });
  }
};
const urgeSignLoading = ref(false);
const expeditingSign = async () => {
  urgeSignLoading.value = true;
  try {
    await urgeSign({
      businessId: taskInfo.value.taskId,
    });
    uni.showToast({
      title: '催签成功',
      icon: 'none',
      duration: 2000,
    });
    urgeSignLoading.value = false;
  } catch {
    urgeSignLoading.value = false;
  }
};

const taskId = ref<any>({});
const projectInfo = ref<any>({});
const tab = ref<string>('');
onLoad(() => {
  const {
    taskId: tId,
    projectInfo: pInfo,
    tab: _tab,
  } = (uni as any).$Router.getQuery();
  tab.value = _tab;
  taskId.value = tId;
  getTaskInfo(taskId.value);
  projectInfo.value = pInfo;
});
const refFileList = ref();
function socketInit(res: any) {
  console.log(res, 'socket info');
  if (res.businessType === 13) {
    refFileList.value[0]?.reloadData();
  }
  if (res.businessType === 14) {
    getTaskInfo(taskId.value);
    refFileList.value[0]?.reloadData();
  }
}
function offSocketInfo() {
  console.log('off socket');
  uni.$off('socket_message', socketInit);
}
onMounted(() => {
  console.log('on socket');
  uni.$on('socket_message', socketInit);
});
onUnmounted(() => {
  offSocketInfo();
});

useBack(() => {
  if (uni.getStorageSync('toFileList') === '1') {
    if (tabList.value.some((item) => item.name === '文件清单')) {
      current.value = tabList.value.findIndex(
        (item) => item.name === '文件清单'
      );
      swiperCurrent.value = tabList.value.findIndex(
        (item) => item.name === '文件清单'
      );
      uni.removeStorageSync('toFileList');
    }
  } else {
    getTaskInfo(taskId.value);
  }
});
</script>
<style lang="scss">
.swiper {
  height: calc(100vh - 200rpx - env(safe-area-inset-bottom));
  .content-page {
    height: calc(100vh - 224rpx - env(safe-area-inset-bottom));
  }
  &.noButton {
    height: calc(100vh - 100rpx - env(safe-area-inset-bottom));
    .content-page {
      height: calc(100vh - 124rpx - env(safe-area-inset-bottom));
    }
  }
}

.btn-box {
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  position: fixed;
  z-index: 10;
}
</style>
